package cn.calm.xhtml.impl;

import javax.el.ExpressionFactory;
import javax.el.PropertyNotFoundException;
import javax.el.ValueExpression;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.calm.xhtml.api.service.XhtmlContext;
import de.odysseus.el.ExpressionFactoryImpl;
import de.odysseus.el.util.SimpleContext;

public class JuelXhtmlContext extends XhtmlContext {
	private static final Logger LOGGER = LoggerFactory.getLogger(JuelXhtmlContext.class);
	private ExpressionFactory factory = new ExpressionFactoryImpl();
	private SimpleContext expressContext = new SimpleContext();

//	public JuelXhtmlContext(TemplateEngine templateEngine,
//			ResponseWriter responseWriter) {
//		super(templateEngine, responseWriter);
//	}

	public SimpleContext getExpressContext() {
		return expressContext;
	}

	public void setExpressContext(SimpleContext expressContext) {
		this.expressContext = expressContext;
	}
	public void setValue(String var, Object value) {
//		Class<?> clazz;
//		if (value == null) {
//			clazz = Object.class;
//		} else {
//			clazz = value.getClass();
//		}
//		ValueExpression e = factory.createValueExpression(value, Object.class);
		getExpressContext().getELResolver().setValue(getExpressContext(), null, var, value);
	}

	public ExpressionFactory getFactory() {
		return factory;
	}

	public void setFactory(ExpressionFactory factory) {
		this.factory = factory;
	}

	@Override
	public Object getValue(String express) {
		try {
			LOGGER.info("value express:"+express);
			ValueExpression createValueExpression = factory.createValueExpression(expressContext, express, Object.class);
			Object value = createValueExpression.getValue(expressContext);
			LOGGER.info("value express value="+value);
			return value;
		} catch (PropertyNotFoundException e) {
			//LOGGER.info("", e);
			ValueExpression expression = expressContext.getVariableMapper().resolveVariable(express);
			if(expression == null){
				LOGGER.info("value express value= null");
				return null;
			}
			Object value = expression.getValue(expressContext);
			if(value==null){
				LOGGER.info("value express value= null");
				return null;
			}
			return value;
			
		}
	}
}
